package cc.siyecao.fastdfs.command.tracker;

import cc.siyecao.fastdfs.command.Command;
import cc.siyecao.fastdfs.model.RecvPackageInfo;
import cc.siyecao.fastdfs.protocol.ProtocolConstants;
import cc.siyecao.fastdfs.util.ProtocolUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 移除存储服务器命令
 *
 * @author lyt
 */
public class DeleteStorageCommand extends FdfsTrackerCommand<Integer> {

    public DeleteStorageCommand(String groupName, String storageIpAddr) {
        this.groupName = groupName;
        this.storageIpAddr = storageIpAddr;
    }

    @Override
    protected void send(OutputStream out, Charset charset) throws Exception {
        byte[] header;
        byte[] bGroupName;
        byte[] bs;
        int len;
        bs = groupName.getBytes( charset );
        bGroupName = new byte[ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN];

        if (bs.length <= ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN) {
            len = bs.length;
        } else {
            len = ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN;
        }
        Arrays.fill( bGroupName, (byte) 0 );
        System.arraycopy( bs, 0, bGroupName, 0, len );

        int ipAddrLen;
        byte[] bIpAddr = storageIpAddr.getBytes( charset );
        if (bIpAddr.length < ProtocolConstants.FDFS_IPADDR_SIZE) {
            ipAddrLen = bIpAddr.length;
        } else {
            ipAddrLen = ProtocolConstants.FDFS_IPADDR_SIZE - 1;
        }

        header = ProtocolUtil.packHeader( Command.TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE, ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN + ipAddrLen, (byte) 0 );
        byte[] wholePkg = new byte[header.length + bGroupName.length + ipAddrLen];
        System.arraycopy( header, 0, wholePkg, 0, header.length );
        System.arraycopy( bGroupName, 0, wholePkg, header.length, bGroupName.length );
        System.arraycopy( bIpAddr, 0, wholePkg, header.length + bGroupName.length, ipAddrLen );
        out.write( wholePkg );
    }

    @Override
    protected Integer receive(InputStream in, Charset charset) throws Exception {
        RecvPackageInfo pkgInfo = ProtocolUtil.recvPackage( in, Command.TRACKER_PROTO_CMD_RESP, 0 );
        if (pkgInfo.errno != 0) {
            return Integer.valueOf( this.errno );
        }
        return 0;
    }
}
